import { join } from 'path';
import { readdirSync } from 'fs';
import { Browser, Page, BrowserContext } from 'playwright';

interface Plugin {
  name: string;
  openBrowser: (url: string, headless: boolean) => Promise<{ browser: Browser, page: Page, context: BrowserContext }>;
  batchReject: (browser: Browser, page: Page, orderNumbers: string[]) => Promise<void>;
}

class PluginManager {
  private plugins: { [key: string]: Plugin } = {};

  constructor(private pluginDir: string) {}

  async loadPlugins() {
    const pluginFolders = readdirSync(this.pluginDir, { withFileTypes: true })
      .filter(dirent => dirent.isDirectory())
      .map(dirent => dirent.name);

    for (const pluginName of pluginFolders) {
      await this.loadPlugin(pluginName);
    }
  }

  async loadPlugin(pluginName: string) {
      // 构造插件的路径，指向插件的入口文件
    const pluginPath = join(this.pluginDir, pluginName, 'index.ts');
    try {
      // 动态导入插件模块，以便于在运行时加载
      const pluginModule = await import(pluginPath);
      // 将插件的重要方法集成到系统中
      this.plugins[pluginName] = {
        name: pluginName,
        openBrowser: pluginModule.openBrowser,
        batchReject: pluginModule.batchReject,
      };
    } catch (error) {
      console.error(`Failed to load plugin ${pluginName}:`, error);
    }
  }

  getPlugin(pluginName: string): Plugin | undefined {
    return this.plugins[pluginName];
  }
}

export default PluginManager;